package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;

//线程1:a
//线程2:b
//线程3:c

//线程1:a
//线程2:b
//线程3:c

//线程1:a
//线程2:b
//线程3:c
// 等待标记      输出内容   修改标记为
//    1            a         2
//    2            b         3
//    3            c         1
@Slf4j(topic = "c.Test48_$$$$$_设计模式之顺序控制_wait_notify实现3个线程交替输出abc五次")
public class Test48_$$$$$_设计模式之顺序控制_wait_notify实现3个线程交替输出abc五次 {

    public static void main(String[] args) {
        WaitNotify1 waitNotify1 = new WaitNotify1(1, 5);
        Thread a = new Thread(() -> {
            waitNotify1.print("a", 1, 2);
        }, "a");

        Thread b = new Thread(() -> {
            waitNotify1.print("b", 2, 3);
        }, "b");

        Thread c = new Thread(() -> {
            waitNotify1.print("c", 3, 1);
        }, "c");
        a.start();
        b.start();
        c.start();
    }
}
//等待标记
@Slf4j(topic = "c.WaitNotify1")
class WaitNotify1{
    //等待标记
    private int waitFlag;
    //循环次数
    private int loopNumber;

    public WaitNotify1(int waitFlag, int loopNumber) {
        this.waitFlag = waitFlag;
        this.loopNumber = loopNumber;
    }

    //打印
    //线程1传过来 a 1 2
    //先比较和waitFlag是否一致，不一致等待
    public void print(String str,int waitFlag,int nextFlag){
        for (int i = 0; i < this.loopNumber; i++) {
            synchronized (this) {
                while (this.waitFlag != waitFlag) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(str);
                this.waitFlag = nextFlag;
                this.notifyAll();
            }
        }
    }
}
